﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.IO;
using System.Xml.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CarBooker.Controllers;
using System.Data.SqlClient;
using System.Drawing;
using System.Xml;
using System.Xml.Serialization;
using System.Text;

namespace CarBooker.Models
{
    public class CarRepository
    {
        public List<Car> Cars { get; set; }
        public CarRepository()
        {
            Cars = new List<Car>();
        }
    }

    public class CarService : ICarService
    {
        CarRepository carList = new CarRepository();

        public List<Car> AvailableCars(BookingRequest enquiry)
        {
            return enquiry.FindAvailableCars(carList);
        }
        public void BookCar() { }
        public void AddCar(CarDescription description)
        {
            //carList.Cars.Add(new Car(description));
            AddCarToDB(description);

        }
        public void AddCarToDB(CarDescription description)
        {
            string xml;

            XmlSerializer serial = new XmlSerializer(typeof(CarDescription));
            using (MemoryStream stream = new MemoryStream())
            {
                using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
                {
                    serial.Serialize(writer, description);
                    xml = Encoding.UTF8.GetString(stream.GetBuffer());
                }
            }
            string connString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Code\GoogleCode\bookcar\branches\InitialCarBooker\CarBooker\App_Data\CarBooker.mdf;Integrated Security=True;User Instance=True";
            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand("INSERT INTO CAR(Description) VALUES (@CarDescription)");
                cmd.Parameters.AddWithValue("CarDescription", xml);
                cmd.Connection = conn;
                conn.Open();
                cmd.ExecuteNonQuery();
            }

        }
    }

    public interface ICarService
    {
        List<Car> AvailableCars(BookingRequest enquiry);
        void BookCar();
        void AddCar(CarDescription description);
    }
}